<template>
  <div class="page-container">
    <el-card class="full-card">
      <div class="main-box">
        <!--左边树-->
        <div class="custom-tree-container">
          <div class="block">
            <div>
              <span>词库分类</span>
              <el-button
                type="text"
                size="mini"
                @click="openLibTypeDialog(undefined)"
              >
                添加类别
              </el-button>
              <el-button
                type="text"
                size="mini"
                @click="this.fetchTreeData"
              >
                刷新
              </el-button>
            </div>
            <el-tree
              :data="treeData"
              default-expand-all
              :expand-on-click-node="false"
              @node-click="handleNodeClick"
            >
              <div class="custom-tree-node" slot-scope="{ node, data }">
                <span>{{ node.label }}</span>
                <div>
                  <!-- 添加按钮 -->
                  <el-tooltip content="添加新的子类别" placement="top">
                    <el-button
                      type="text"
                      size="mini"
                      icon="el-icon-plus"
                      @click="() => openLibTypeDialog(data.id)"
                    />
                  </el-tooltip>

                  <!-- 删除按钮 -->
                  <el-tooltip content="删除该类别" placement="top">
                    <el-button
                      type="text"
                      size="mini"
                      icon="el-icon-minus"
                      @click="() => remove(node, data)"
                    />
                  </el-tooltip>
                </div>

              </div>
            </el-tree>
          </div>
        </div>

        <!--右边列表-->
        <div class="right-list">
          <div class="list-title-div"><span>{{ treeNode.label }} 单词信息</span></div>
          <!-- 操作栏 -->
          <div class="toolbar">
            <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAdd">新增单词</el-button>
            <div class="searBtn">
              <el-input
                v-model="fullSpell"
                placeholder="搜索单词"
                clearable
                @clear="fetchData"
                @keyup.enter.native="fetchData"
              />
              <div class="button-box">
                <el-button type="text" size="mini" @click="fetchData(false)">模糊搜索</el-button>
                <el-button type="text" size="mini" @click="fetchData(true)">精准搜索</el-button>
              </div>
            </div>

          </div>
          <!-- 表格部分：设置高度+overflow -->
          <div class="table-container">
            <el-table
              :data="tableData"
              border
              style="width: 100%"
              height="100%"
            >
              <el-table-column type="index" label="序号" width="50"/>
              <el-table-column prop="fullSpell" label="单词全拼">
                <template #default="{row}">
                  <div style="display: flex;align-items: center">
                    <el-tag style="cursor: pointer">{{ row.fullSpell }}</el-tag>
                    <audio-playback style="margin-left: 5px" :word-id="row.id"/>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="sequence" label="词性"/>
              <el-table-column prop="rootSummary" label="释义" show-overflow-tooltip/>
              <el-table-column prop="createTime" label="添加时间" min-width="100"/>
              <el-table-column label="操作" width="180">
                <template #default="{row}">
                  <el-button size="mini" type="primary" @click="handleEdit(row)">编辑</el-button>
                  <el-button size="mini" type="danger" @click="handleDelete(row.chemicalId)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 分页 -->
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            class="pagination"
            :total="total"
            :page-size="pageSize"
            :page-sizes="[10, 20, 30, 100]"
            :current-page="pageNum"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 弹窗表单 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="chemicalForm" ref="chemicalForm" :rules="rules" label-width="100px">
        <el-form-item label="单词名称" prop="fullSpell">
          <el-input v-model="chemicalForm.fullSpell"/>
        </el-form-item>
        <el-form-item label="规格" prop="rootSummary">
          <el-input v-model="chemicalForm.rootSummary"/>
        </el-form-item>
        <el-form-item label="危险等级" prop="difficultyLevel">
          <el-input v-model="chemicalForm.difficultyLevel"/>
        </el-form-item>
        <el-form-item label="存储位置" prop="occurrence">
          <el-input v-model="chemicalForm.occurrence"/>
        </el-form-item>
        <el-form-item label="计量单位" prop="unit">
          <el-input v-model="chemicalForm.unit"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>

    <add-category-dialog
      :visible.sync="libTypeDialogVisible"
      :parent-id="currentParentId"
      @submit="handleSubmitCategory"
    />
  </div>
</template>

<script>
import AudioPlayback from '@/views/component/audioPlayback.vue'
import AddCategoryDialog from '@/views/wordLibrary/teachingWordLibrary/primarySchool/AddCategoryDialog.vue'
import { deleteById, saveOrUpdate, selectTreeList } from '@/api/wordSystemWordLibType'
import { auto } from 'html-webpack-plugin/lib/chunksorter'

export default {
  components: { AddCategoryDialog, AudioPlayback },
  data() {
    return {
      treeData: [],
      libTypeDialogVisible: false,
      currentParentId: '',
      treeNode: {},
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      dialogTitle: '新增单词',
      fullSpell: '',
      chemicalForm: {
        chemicalId: null,
        fullSpell: '',
        rootSummary: '',
        difficultyLevel: '',
        occurrence: '',
        unit: ''
      },
      rules: {
        fullSpell: [{ required: true, message: '请输入单词名称', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.fetchTreeData()
    this.fetchData()
  },
  methods: {
    auto,
    fetchTreeData() {
      selectTreeList().then(res => {
        this.treeData = res
      })
    },
    fetchData(exactMatch) {
      selectPage({
        page: { pageNum: this.pageNum, pageSize: this.pageSize },
        param: { fullSpell: this.fullSpell, exactMatch: !!exactMatch }
      }).then(res => {
        console.log(res)

        this.tableData = res.records
        this.total = res.total * 1
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.pageNum = val
      this.fetchData()
    },
    handleNodeClick(data) {
      this.treeNode = data
    },
    handleAdd() {
      this.dialogTitle = '新增单词'
      this.chemicalForm = {
        id: null,
        name: '',
        code: '',
        type: '',
        price: null,
        quantity: null
      }
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑单词信息'
      this.chemicalForm = Object.assign({}, row)
      this.dialogVisible = true
    },
    handleDelete(id) {
      this.$confirm('确定删除该单词吗？', '提示', {
        type: 'warning'
      }).then(() => {
        deleteChemical(id).then(() => {
          this.$message.success('删除成功')
          this.fetchData()
        })
      }).catch(() => {
      })
    },
    handleSubmit() {
      this.$refs.chemicalForm.validate(valid => {
        if (valid) {
          if (this.chemicalForm.chemicalId) {
            updateChemical(this.chemicalForm.chemicalId, this.chemicalForm).then(() => {
              this.$message.success('更新成功')
              this.dialogVisible = false
              this.fetchData()
            })
          } else {
            createChemical(this.chemicalForm).then(() => {
              this.$message.success('新增成功')
              this.dialogVisible = false
              this.fetchData()
            })
          }
        }
      })
    },

    openLibTypeDialog(parentId) {
      this.currentParentId = parentId
      this.libTypeDialogVisible = true
    },
    remove(node, data) {
      this.$confirm('确定删除该分类吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteById({ id: data.id }).then(() => {
          this.$message.success('删除成功')
          this.fetchTreeData()
          this.fetchData()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSubmitCategory({ name, parentId }) {
      console.log('提交类别:', name, '父ID:', parentId)
      const reqData = { label: name, parentId: parentId, rootLibType: undefined }
      if (!parentId) {
        reqData.rootLibType = 'primarySchool'
      }
      saveOrUpdate(reqData).then(res => {
        this.$message.success(name + '类别保存成功')
        this.fetchTreeData()
      })
    }
  }
}
</script>
<style scoped>
.page-container {
  height: calc(100vh - 50px);
  padding: 20px;
  box-sizing: border-box;
}

.full-card {
  height: 100%;
}

.main-box {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.table-container {
  flex: 1;
  overflow: hidden;
  height: calc(100vh - 235px);
  width: 100%;
}

/* 保证分页栏不被挤压 */
.pagination {
  margin-top: 10px;
  text-align: right;
}

.searBtn {
  display: flex;
  align-items: stretch; /* 让右侧按钮盒子和输入框等高 */
  gap: 8px; /* 输入框与按钮之间的间距，可根据需要调整 */
}

.searBtn /deep/ .el-input__inner {
  padding: 0 0 0 15px;
}

.button-box {
  display: flex;
  flex-direction: column; /* 垂直排列按钮 */
  justify-content: space-between; /* 让按钮平分高度 */
  height: 100%; /* 高度继承自父容器，即输入框 */
}

.button-box .el-button {
  flex: 1; /* 平分按钮高度 */
  margin: 0; /* 去除按钮间外边距 */
  padding: revert
}

.toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.toolbar .el-button {
  padding: unset;
  width: 72px;
  height: 32px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.right-list {
  width: 84%;
  padding-left: 10px;
  border-left: 1px solid #3498db;
}

.custom-tree-container {
  overflow-x: auto;
  white-space: nowrap;
}

.block {
  //min-width: max-content;
  min-width: 250px;
}

.list-title-div {
  display: flex;
  justify-content: center;
  border-bottom: 1px solid coral;
  margin: 0 0 5px 0;

  span {
    font-size: 16px;
    font-weight: bold;
    color: coral;
  }
}
</style>

